#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
typedef unsigned long MSIHANDLE;
#include "../ca/pgmsi.h"

__declspec(dllexport)
UINT __stdcall LaunchPginst(MSIHANDLE hInstall)
{
	char curdir[1024],lang[1024],trans[1024];
	char writelog[1024];
	char cmd[2048];
	DWORD szbuf = sizeof(curdir);
	STARTUPINFO si;
	PROCESS_INFORMATION pi;

	ZeroMemory(curdir,sizeof(curdir));
	if (MsiGetPropertyA(hInstall,"SourceDir",curdir,&szbuf) != ERROR_SUCCESS)
	{
		MessageBox(0,"wrapper failed to get SourceDir property!",NULL,0);
		return ERROR_INSTALL_FAILURE;
	}

	szbuf = sizeof(lang);
	ZeroMemory(lang,sizeof(lang));
	if (MsiGetPropertyA(hInstall,"LanguageChoice",lang,&szbuf) != ERROR_SUCCESS)
	{
		MessageBox(0,"wrapper failed to get LanguageChoice property!",NULL,0);
		return ERROR_INSTALL_FAILURE;
	}

	szbuf = sizeof(writelog);
	ZeroMemory(writelog,sizeof(writelog));
	if (MsiGetPropertyA(hInstall,"WRITELOG",writelog,&szbuf) != ERROR_SUCCESS)
	{
		MessageBox(0,"wrapper failed to get WRITELOG property!",NULL,0);
		return ERROR_INSTALL_FAILURE;
	}

	ZeroMemory(&si,sizeof(si));
	ZeroMemory(&pi,sizeof(pi));
	si.cb = sizeof(si);

	if (curdir[strlen(curdir)-1] == '\\')
		curdir[strlen(curdir)-1] = 0;

	if (strcmp(lang,"en"))
		wsprintf(trans,"TRANSFORMS=:lang_%s", lang);
	else
		trans[0] = 0;

	if (!strcmp(writelog,"1"))
	{
		/* Write logfile */
		wsprintf(writelog,"/l*v \"%s\\postgresql-" PGVER ".log\"", curdir);
	}
	else 
	{
		/* Don't write logfile, so clear the variable if it contains some
		   other junk. */
		writelog[0] = 0;
	}

	wsprintf(cmd,"msiexec.exe %s /i \"%s\\postgresql-" PGVER "-int.msi\" %s INTERNALLAUNCH=1 INSTALLLANG=%s", writelog,curdir,trans,lang);
	if (CreateProcess("msiexec.exe",cmd, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi) == 0)
	{
		char msg[128];

		wsprintf(msg,"Failed to create process: %i!",GetLastError());
		MessageBox(0,msg,NULL,0);
		return ERROR_INSTALL_FAILURE;
	}

	/* 
	 * This can be useful for debugging, but in production we really
	 * don't need to wait here, we can just let the msiexec.exe process
	 * die away.
	 */
	/*
	  if (WaitForSingleObject(pi.hProcess, INFINITE) != WAIT_OBJECT_0)
	  {
	  MessageBox(0,"Failed to wait for subprocess!",NULL,0);
	  return ERROR_INSTALL_FAILURE;
	  }
	*/

	CloseHandle(pi.hThread);
	CloseHandle(pi.hProcess);

	return ERROR_SUCCESS;
}

typedef struct {
	char *langid;
	char *map;
} _langinfo;
static _langinfo langinfo[] = {
#include "langinfo.h"
	{NULL, NULL}
};

__declspec(dllexport)
UINT __stdcall GetDefaultLanguage(MSIHANDLE hInstall)
{
	int num;
	char buf[6];
	_langinfo *lp;

	ZeroMemory(buf,sizeof(buf));
	num = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IDEFAULTLANGUAGE, buf, sizeof(buf));

	for (lp = langinfo; lp->langid; lp++)
	{
		if (!strcmp(lp->map, buf)) 
		{
			MsiSetPropertyA(hInstall,"LanguageChoice",lp->langid);
			return ERROR_SUCCESS;
		}
	}

	return ERROR_SUCCESS;
}
